<template>
  <div class="searchBox">
      <mHeaderVue :isblack="true" :showback="true" :title="'搜索'"></mHeaderVue>
      <mSearchVue @change-title="changeTitle"></mSearchVue>
    <div class="search__main" v-if="state.showSuggest">
      <mSearchHistoryVue 
      :searchHistory="store.state.searchHistory"
      @del-search-history="delSearchHistory" 
      @to-history = "toHistory"
      v-if="showHistory"></mSearchHistoryVue>
      <mSearchHotContentVue 
      :hotSearch="state.hotSearch" 
      @click-hot="clickHot"></mSearchHotContentVue>
    </div>
    <div class="search__suggest" v-else>
      <mSearchSuggestVue 
      :suggestList= "state.suggestList" 
      @to-suggest="toSuggest"></mSearchSuggestVue>
    </div>
  </div>
</template>
<script setup>
import { computed, onMounted, reactive } from "@vue/runtime-core";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import mHeaderVue from "../components/m-header.vue";
import mSearchHistoryVue from "../components/m-search-history.vue";
import mSearchHotContentVue from "../components/m-search-hot-content.vue";
import mSearchSuggestVue from "../components/m-search-suggest.vue";
import mSearchVue from "../components/m-search.vue";
import { getSearchHotSong,getSearchSong } from "../request/api";
// 数据
const state  = reactive({
  hotSearch:[],
  suggestList:[],
  showSuggest:true
})
// vuex
const store = useStore()
// vue-router
const Router = useRouter()

// 从HOT搜索内容变化
const clickHot = (val) =>{
  store.dispatch('changeQuery',val)
}
// 从历史记录增加搜索
const toHistory = (val) =>{
  store.dispatch('changeQuery',val)
}
const changeTitle = async (val) =>{
  store.dispatch('changeQuery',val)
  if(!val){  
    state.showSuggest = true
    return
  }
  state.showSuggest = false
  let res = await   getSearchSong({keywords:val})
  state.suggestList =  res.result.songs
  // 请求数据后将数据存放到VUEX中
  pushSearchHistory(val)
}

// 跳转至播放页面
const toSuggest = (val)=>{
  Router.push({name:'Play', params:{ids:val}})
}

// 存放搜索数据
const pushSearchHistory = (val) =>{
  // 一存放则返回
  if(store.state.searchHistory.includes(val)){
    return 
  }
  store.dispatch('addSearchHistory',val)
}
// 清空搜索历史
const delSearchHistory = () =>{
  store.dispatch('clearSearchHistory')
}



// 展示历史记录
const showHistory = computed(()=>{
  if(store.state.searchHistory.length){
    return true
  }
  return false
})




// 获取热搜数据
onMounted(async ()=>{
  const res = await getSearchHotSong()
  state.hotSearch = res.data
})

</script>
<style lang="stylus">
.searchBox
  box-sizing border-box
  overflow hidden
.search__main
  margin-top 20px
  overflow hidden
  overflow-y auto
  height 560px
  border-radius 10px
  padding 0 14px
.search__hot
  margin-top 10px
.search__suggest
  margin-top 10px
  overflow hidden
  overflow-y auto
  height calc(100vh - 50px)
  border-radius 10px
  padding 0 14px


</style>